#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/wait.h>
#define N 100
#define len 100
#define MAX 100
typedef int pid_t;

char* make(char *buf)//将字符串传入参数表内
{
    char *cp;
    cp=malloc(strlen(buf)+1);
    if (cp==NULL)
    {
        fprintf(stderr,"no memory\n");
        exit(1);
    }
    strcpy(cp,buf);
    return cp;
}

int change(char *buf,char *arglist[])//对于字符串进行分割
{
   int num,j,i,last;
    char buffer[len];
    num=0;
    i=0;
    while (num<MAX)
    {
        if (buf[i]=='\n')
        {
            arglist[num]=NULL;
              return num;
           
        }
        if (buf[i]==' ') i++;
        last=i;
        while (buf[i]!=' ' && buf[i]!='\n') i++;
        for (j=last;j<i;j++) buffer[j-last]=buf[j];
        buffer[j-last]='\0';
        arglist[num++]=make(buffer);
    }
    
}

int main(){
 pid_t pid;
 char *arglist[MAX];//shell指令参数表
 char buf[len];
 int x;
 while(1){
  struct passwd *my_info;
  char path[N];
  my_info = getpwuid(getuid());
  getcwd(path, sizeof(path));
  printf("[%s@%s]$ ", my_info->pw_name, path);
  fflush(stdout);
  fgets(buf,len,stdin);//读入单行指令
  x=change(buf,arglist);
  pid=fork();//创建一个子进程
  if(pid<0) /* 如果出错 */
               printf("error ocurred!/n");
  if(pid==0){
      execvp(arglist[0],arglist);//执行命令
   }
   waitpid(pid,NULL,0);//等待子进程结束
 }
 return 0;
}


